from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from .. models import Types
import time,os
from django.core.paginator import Paginator
# Create your views here.
# 分类列表
def typeindex(request):
	
	
	
	names = request.GET.get('type',None)
	
	if names == 'name':
		ob = Types.objects.filter(name__contains=request.GET.get('keywords',''))
	else:
		ob = Types.objects.filter().order_by('id')

	paginator = Paginator(ob,5)
	p = int(request.GET.get('p',1))
	
	typelist= paginator.page(p)

	
	context = {'types':typelist,'p':p,}
	return render(request,'myadmin/type/index.html',context)


# 分类添加
def typeadd(request):
	ob = Types.objects.all()
	context = {'types':ob}
	return render(request,'myadmin/type/add.html',context)
# 添加处理
def typeinsert(request):
	try:
		
		ob = Types()
		ob.name = request.POST['name']
		ob.pid = request.POST['pid']
		# 判断是否为顶级分类
		if ob.pid == '0':
			ob.path = '0,'
		else:
		    # 查询当前父级的path
			p = Types.objects.get(id=ob.pid)
			ob.path = p.path+ob.pid+','
		# 执行添加
		ob.save()
		return HttpResponse('<script>alert("添加成功");location.href="/admin/typeindex"</script>')
	except:
		return HttpResponse('<script>alert("添加失败");location.href="/admin/typeadd"</script>')
	
# 封装函数,查询所有分类
def typegetall():
	ob = Types.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')
	for x in ob:
		n = len(x.path) - 2
		w = int(n/2)
		x.name = (w*'|___')+x.name
	return ob


def typedel(request,tid):
	# return HttpResponse('1')
	num = Types.objects.filter(pid=tid).count()
	if num:
		return HttpResponse('<script>alert("当前分类有子类,不能删除");location.href="/admin/typeindex"</script>')
	else:
		ob = Types.objects.get(id=tid)

		ob.delete()
	
	return HttpResponse('<script>alert("删除成功");location.href="/admin/typeindex"</script>')

# 分类修改
def typeedit(request,tid):
	# 获取所有分类
	obs = typegetall()
	# 查询分类信息
	ob = Types.objects.get(id=tid)
	
	context = {'tinfo':ob,'typelist':obs}
	return render(request,'myadmin/type/edit.html',context)

# 修改处理
def typeupdate(request):
	
	try:
		ob = Types.objects.get(id=request.POST['tid'])
		ob.name = request.POST['name']
		
		ob.save()
	
		return HttpResponse('<script>alert("修改成功");location.href="/admin/typeindex"</script>')
	except:
		return HttpResponse('<script>alert("修改失败");location.href="/admin/typeindex/'+ob.id+'"</script>')











